// 安全工具函数：防止XSS和SQL注入

/**
 * 清理HTML字符，防止XSS攻击
 * @param {string} str - 要清理的字符串
 * @returns {string} 清理后的字符串
 */
export function sanitizeInput(str) {
  if (typeof str !== 'string') {
    return str;
  }
  
  return str
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#x27;')
    .replace(/\//g, '&#x2F;');
}

/**
 * 验证输入是否只包含安全的字符
 * @param {string} str - 要验证的字符串
 * @param {Object} options - 验证选项
 * @returns {boolean} 是否安全
 */
export function validateInput(str, options = {}) {
  if (!str || typeof str !== 'string') {
    return false;
  }

  const {
    allowNumbers = true,
    allowLetters = true,
    allowChinese = true,
    allowSpecial = '',
    maxLength = 1000
  } = options;

  // 长度检查
  if (str.length > maxLength) {
    return false;
  }

  // 构建允许的字符模式
  let pattern = '';
  if (allowNumbers) pattern += '0-9';
  if (allowLetters) pattern += 'a-zA-Z';
  if (allowChinese) pattern += '\\u4e00-\\u9fa5';
  if (allowSpecial) pattern += allowSpecial;

  const regex = new RegExp(`^[${pattern}\\s\\-\\_\\u3000-\\u303F]+$`, 'u');
  return regex.test(str);
}

/**
 * 验证身份证号格式
 * @param {string} idCard - 身份证号
 * @returns {boolean} 是否有效
 */
export function validateIdCard(idCard) {
  const pattern = /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1])\d{3}[0-9Xx]$/;
  return pattern.test(idCard);
}

/**
 * 验证手机号格式
 * @param {string} phone - 手机号
 * @returns {boolean} 是否有效
 */
export function validatePhone(phone) {
  const pattern = /^1[3-9]\d{9}$/;
  return pattern.test(phone);
}

/**
 * 验证邮箱格式
 * @param {string} email - 邮箱
 * @returns {boolean} 是否有效
 */
export function validateEmail(email) {
  const pattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return pattern.test(email);
}

/**
 * 清理所有输入数据，防止注入攻击
 * @param {Object} data - 要清理的数据对象
 * @returns {Object} 清理后的数据对象
 */
export function sanitizeFormData(data) {
  const sanitized = {};
  
  for (const [key, value] of Object.entries(data)) {
    if (value === null || value === undefined) {
      sanitized[key] = value;
      continue;
    }
    
    if (typeof value === 'string') {
      // 对于文本输入，进行清理
      sanitized[key] = value.trim().replace(/[<>&"']/g, '');
    } else if (Array.isArray(value)) {
      // 对于数组，递归清理每个元素
      sanitized[key] = value.map(item => 
        typeof item === 'string' ? item.trim().replace(/[<>&"']/g, '') : item
      );
    } else {
      sanitized[key] = value;
    }
  }
  
  return sanitized;
}

/**
 * 验证是否包含危险的SQL关键字
 * @param {string} str - 要检查的字符串
 * @returns {boolean} 是否包含危险字符
 */
export function containsDangerousSQL(str) {
  if (typeof str !== 'string') return false;
  
  const dangerousKeywords = [
    'SELECT', 'INSERT', 'UPDATE', 'DELETE', 'DROP', 'CREATE', 'ALTER',
    'EXEC', 'EXECUTE', 'UNION', 'SCRIPT', 'JAVASCRIPT', 'ONLOAD', 'ONERROR'
  ];
  
  const upperStr = str.toUpperCase();
  return dangerousKeywords.some(keyword => upperStr.includes(keyword));
}

/**
 * 速率限制验证（防止提交过快）
 */
export class RateLimiter {
  constructor(maxRequests = 5, timeWindow = 60000) {
    this.maxRequests = maxRequests;
    this.timeWindow = timeWindow;
    this.requests = new Map();
  }

  check(identifier) {
    const now = Date.now();
    const userRequests = this.requests.get(identifier) || [];

    // 清理过期请求
    const recentRequests = userRequests.filter(time => now - time < this.timeWindow);

    if (recentRequests.length >= this.maxRequests) {
      return false;
    }

    recentRequests.push(now);
    this.requests.set(identifier, recentRequests);
    return true;
  }

  reset(identifier) {
    this.requests.delete(identifier);
  }
}

export default {
  sanitizeInput,
  validateInput,
  validateIdCard,
  validatePhone,
  validateEmail,
  sanitizeFormData,
  containsDangerousSQL,
  RateLimiter
};

